package com.jastar.android.util;

import android.content.Context;
import android.media.MediaPlayer;

import java.util.Objects;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

public class AudioPlayer {

    private static final AudioPlayer player = new AudioPlayer();
    private static final int MAX_PLAY = 6;

    private final Executor executor = Executors.newFixedThreadPool(3);
    private final AtomicLong audioTag = new AtomicLong(0L);
    private MediaPlayer mediaPlayer;

    private AudioPlayer() {
    }

    public static AudioPlayer getPlayer() {
        return player;
    }

    public void stop() {
        audioTag.set(System.currentTimeMillis());
    }

    public synchronized void playOnce(Context context, int audioId, BaseListener<Integer> completionListener) {
        Context appContext = context.getApplicationContext();
        if (null != mediaPlayer) release(mediaPlayer);
        mediaPlayer = createPlayer(appContext, audioId, completionListener);
        mediaPlayer.start();
    }

    private MediaPlayer createPlayer(Context appContext, int audioId, BaseListener<Integer> completionListener) {
        MediaPlayer player = MediaPlayer.create(appContext, audioId);
        player.setOnCompletionListener(mp -> {
            if (null != completionListener) completionListener.onEvent(audioId);
        });
        return player;
    }

    public void play(Context context, int audioId) {
        executor.execute(() -> {
            int times = 0;
            long currentAudio = System.currentTimeMillis();
            audioTag.set(currentAudio);
            Utils.sleep(1000);
            do {
                playOnce(context, audioId, null);
                Utils.sleep(3000);
            } while (Objects.equals(audioTag.get(), currentAudio) && (++times) < MAX_PLAY);
        });
    }

    public void release(MediaPlayer player) {
        player.stop();
        player.release();
    }

}
